import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { UserEntity } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class UserService {
  // 使用InjectRepository装饰器并引入Repository这样就可以使用typeorm的操作了
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {}

  create(createUserDto: CreateUserDto) {
    return 'This action adds a new user';
  }

  // 获取所有用户数据列表(userRepository.query()方法属于typeoram)
  async findAll(
    pageNum: number,
    pageSize: number,
  ): Promise<{
    code: number;
    data: UserEntity[];
    total: number;
  }> {
    const startIndex = (pageNum - 1) * pageSize;
    pageSize = typeof pageSize === 'string' ? parseInt(pageSize) : pageSize;
    const data = await this.userRepository.query(
      'SELECT * FROM book_user LIMIT ? OFFSET ?',
      [pageSize, startIndex],
    );
    const total = data.length; // 这里假设直接返回的 data 数组长度即为总数
    const code = 200;
    return { code, data, total };
  }

  // 获取所有用户数据列表(userRepository.query()方法属于typeoram)
  async findOne(
    uid: number,
    pageNum: number,
    pageSize: number,
  ): Promise<{
    code: number;
    data: UserEntity[];
    total: number;
  }> {
    const startIndex = (pageNum - 1) * pageSize;
    pageSize = typeof pageSize === 'string' ? parseInt(pageSize) : pageSize;
    const data = await this.userRepository.query(
      'SELECT * FROM book_user WHERE id = ? LIMIT ? OFFSET ?',
      [uid, pageSize, startIndex],
    );
    const total = data.length; // 这里假设直接返回的 data 数组长度即为总数
    const code = 200;
    return { code, data, total };
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
}
